<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== itellico Net Architect ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 24.04.2005
    * @copyright itellico.com 2005
    *
    *********************************************************/
    
    /***
    * Class clientNodeIfolder
    ****
    * This classs represents a folder for quick ads
    ****
    * @package clientNodes
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @since 06.05.2005
    * @copyright itellico.com 2005
    ***/
    class clientNodeIfolder extends clientNode{
        private $inseratPageType;
        
        /**
         * clientNodeIfolder::process()
         * 
         * Process inputs
         * 
         * @return void 
         **/
        public function process(){
            //turn caching off (temporarily, this has to be fixed somehow)
            $this->smarty->caching = false;
            
            //first figure out the ID of the datatype responsible for inserats
            $this->setInseratPageType();
            
            //first check if there is an add inserat request
            if($_GET['add']){
                $this->addInserat();
                
            //not adding? great, list stuff!
            }else{
                //Check if there is a filter change request
                $filter = $this->getFilter();
                
                //first I need to get the IDs of all child nodes of this folder
                /*
                    Please note, that a whole array of all child nodes is fetched as well,
                    as it will be passed to smarty in order to present on the interface
                    that there exist subfolders in the selected folder
                */
                $myTree     = new tree($this->db,'structure LEFT JOIN objectmap ON structure.id = objectmap.nodeid',$this->log,'id, level, path_cache AS path, title, published_pages');
                $nodes      = $myTree->getChildren($this->node);
                $children   = array();  // list of node IDs that lie below the current node
                $subcats    = array();  // list of direct subcategories i.e. no grandchildren
                
                //mark the level of the subcategories
                if(isset($nodes[0])){
                    $curLevel   = $nodes[0]['level'];
                }
                
                $children[] = $this->node;  //add current node to the set limiter
                
                //loop through the node array and create associate markers to pass to smarty
                foreach($nodes as $node){
                    $children[] = $node['id'];
                    if($node['level'] == $curLevel){
                        $subcats[] = $node;   
                    }
                }
                
                /*
                    create the pager for this iFolder, in order to do this we need to
                    first identify the total number of inserats there are in the
                    currently selected folder
                */
                $total = $this->db->getOne("SELECT count(*)
                                                    FROM pagemap AS pm 
                                                    LEFT JOIN node_inserat AS ni ON pm.pageid = ni.id
                                                    WHERE pm.nodeid IN (".implode(',',$children).") 
                                                    AND pm.wf_state = 1
                                                    AND pm.pagetype = " . $this->inseratPageType . " " . $filter);
                
                $pager = new pager($total,$GLOBALS['_CONFIG']['perpage'],$_GET['pg']);
                
                
                //get inserats for this folder
                /*
                    the call to get the full path to the node may be
                    a bit costly. This procedure may need refactoring
                */
                $inserats   = $this->db->getAll("SELECT 
                                                        pm.created          AS intime,
                                                        pm.title            AS title,
                                                        ni.content          AS content,
                                                        ni.image            AS image,
                                                        ni.id               AS id,
                                                        ni.price            AS price,
                                                        ni.price_type       AS price_type,
                                                        ni.ins_type         AS type,
                                                        get_path(pm.nodeid)||pm.pageurl||'.html' AS url
                                                    FROM pagemap AS pm 
                                                    LEFT JOIN node_inserat AS ni ON pm.pageid = ni.id
                                                    WHERE pm.nodeid IN (".implode(',',$children).") 
                                                    AND pm.pagetype = " . $this->inseratPageType . "
                                                    AND pm.wf_state = 1
                                                    ".$filter." ORDER BY pm.published DESC
                                                    LIMIT ".$GLOBALS['_CONFIG']['perpage']." OFFSET ".$_GET['offset']);
                
                //get folder properties if any
                $data = $this->db->getRow("SELECT * FROM node_inserat_folder WHERE id = ".$this->object);
                $data['title'] = $this->db->getOne("SELECT title FROM objectmap WHERE nodeid = ".$this->node);
                

                //get folder desc data (usable for search engines)
                //note, that this goes UP the tree to the route node
                //until some description is found!
                //$tree = new tree($this->db,'structure LEFT JOIN objectmap ON structure.id = objectmap.nodeid',$this->log,'id');
                $path = $myTree->getPathStack($this->node);
                
                //as $path is an array of arrays, I have to simplify it
                $list = array();
                foreach($path as $node){
                    $list[] = $node['id'];
                }
                
                //now, this is the data I am after
                $data['folder'] = $this->db->getOne("SELECT 
                                                        nif.content 
                                                        FROM structure AS st
                                                        LEFT JOIN objectmap AS om ON st.id = om.nodeid
                                                        LEFT JOIN node_inserat_folder AS nif ON om.objectid = nif.id
                                                        WHERE om.version = 1
                                                        AND nif.content IS NOT NULL
                                                        AND nif.content != ''
                                                        AND st.id IN (".implode(',',$list).")
                                                        ORDER BY st.lft DESC
                                                        LIMIT 1");

                //get actual folder data
                //assign all this stuff to smarty
                $this->smarty->assign(array(
                                        'childFolders'  => $subcats,
                                        'inserats'      => $inserats,
                                        'pager'         => $pager->getPager(),
                                        'data'          => $data));

                
                
            }
        }


        /* --------------------- ADDITION OF NEW LISTING ------------------------- */
        
        /**
         * Adds a new inserat into the database
         * @return void
         */
        private function addInserat(){
            //init error array
            $errors = array();
            
            //first load a different page
            $this->setActionTemplate('inseratAdd.html');
            
            //turn caching off
            $this->smarty->caching = false;
            
            //get some lang data
            $this->smarty->loadLang('inserat.txt','inseratActions');
                
            //get a tree path to this node
            //this is neccessary to get the "posting to foo > bar"
            //dialog on the add post page
            $tempCrumbs = $this->crumbs->getCrumbs();
            
            //get rid of the link to the home page
            array_shift($tempCrumbs);
            
            //pass this stuff to smarty
            $this->smarty->assign('postingTo',$tempCrumbs);
            
            //also mark this step with a breadcrumb
            $this->crumbs->push($this->smarty->lang['add'],'?add=true');

            //check if there is a POST submission!
            if($_POST){
            
                //cast some useful objects
                $parser             = new safeHTMLwrap();
                
                //clean inputs
                $_POST['type']      = (int)$_POST['type'];
                $_POST['pricenum']  = (int)$_POST['pricenum'];
                $_POST['pricealt']  = (int)$_POST['pricealt'];
                $_POST['title']     = trim($_POST['title']);
                $_POST['desc']      = nl2br($parser->parse(strip_tags(trim($_POST['desc']),'<i>,<b>,<u>,<img>')));
                $_POST['mail']      = htmlspecialchars(trim($_POST['mail']));
                $_POST['confNum']   = (int)$_POST['confNum'];

                $_POST['desc']      = preg_replace('#[^\"=]http://([^\s]*)#', '[link]', $_POST['desc']);
				$_POST['desc']      = preg_replace('#^http://([^\s]*)#', '[link]', $_POST['desc']);
                $_POST['desc']      = str_replace('[link] />','[link] <br />',$_POST['desc']);
                    

                
                //check for errors
                //the item must have a title!
                if(empty($_POST['title'])){
                    $errors['title'] = true;   
                }
                
                //make sure there is some description
                if(empty($_POST['desc'])){
                    $errors['desc'] = true;   
                }
                
                //checks for a valid price
                if($_POST['pricenum'] < 0 and $_POST['pricealt']==0){
                    $errors['pricenum'] = true;   
                }
                
                //check for a valid e-mail
                if(empty($_POST['mail']) or !eregi('[-a-zA-Z0-9_\.]{1,}@[-a-zA-Z0-9_\.]{2,}\.[-a-zA-Z0-9_\.]{2,4}',$_POST['mail'])){
                    $errors['mail'] = true;   
                }
                
                //check for a valid confirmation number
                if(!$_POST['key'] and (empty($_POST['confNum']) or $_SESSION['botNumber'] != $_POST['confNum'])){
                    $errors['confNum'] = true;   
                }
                
                //check if the picture is the right weight
                if($_FILES and $_FILES['pict']['error'] == 2){
                    $errors['image'] = true;   
                }else if($_FILES and $_FILES['pict']['error'] == 0){
                    //check if the image is a jpeg
                    $imageData = @getimagesize($_FILES['pict']['tmp_name']);
                    
                    if(!isset($imageData[2]) or $imageData[2] != 2){
                        $errors['image2'] = true; 
                    }
                }

                //are there errors?
                if(empty($errors)){ //no
                    //create confirmation string
                    $confirmCode        = rand(1,99999).uniqid('ins');
                    
                    //see if the price type needs alteration
                    if($_POST['pricenum'] == 0 and $_POST['pricealt'] == 0){
                        $_POST['pricealt'] = 4;
                    }
                    
                    //see if ZIP needs alteration
                    $_POST['zip'] = (int)$_POST['zip'];
                    if($_POST['zip'] == 0){
                        $_POST['zip'] = 'NULL';   
                    }
                
                    //insert data into database
                    if($_FILES and $_FILES['pict']['size'] > 0){ //there was an image submission!!!
                        $imageFlag = 'TRUE'; //prepare the image flag for the database
                        
                    }else{ //there was no image submission =(
                        $imageFlag = 'FALSE'; //prepare the image flag for the database
                    }
                    
                    //start transaction
                    $this->db->StartTrans();
                    
                    //insert page
                    //$this->db->debug = 1;
                    $this->db->Execute("INSERT INTO node_inserat(title,content,owner_mail,owner_code,ins_type,price_type,price,image,zip) VALUES(
                                                                        ".$this->db->qstr($_POST['title']).",
                                                                        ".$this->db->qstr($_POST['desc']).",
                                                                        ".$this->db->qstr($_POST['mail']).",
                                                                        ".$this->db->qstr($confirmCode).",
                                                                        ".$this->db->qstr($_POST['type']).",
                                                                        ".$this->db->qstr($_POST['pricealt']).",
                                                                        ".$this->db->qstr($_POST['pricenum']).",
                                                                        ".$imageFlag.",
                                                                        ".(int)$_POST['zip']."
                                                                    )");
                    
                    //fetch the ID of the freshly inserted page
                    $pageID = $this->db->getOne("SELECT last_value FROM node_inserat_id_seq");
                    
                    //insert page reference
                    $myPageMap = new pageInserter($this->db);
                    $pageURL = $myPageMap->addPageMap($this->node,$pageID,$this->inseratPageType,$_POST['title']);
                    
                    //end transaction
                    $this->db->CompleteTrans();
                    
                    //upload picture (now we can do it, as we have a page id as well)
                    if($imageFlag == 't'){
                        //path to where the image is going to be stored
                        $imagePath = ROOT.'files'.DIRECTORY_SEPARATOR.'inserats'.DIRECTORY_SEPARATOR.date('Y').DIRECTORY_SEPARATOR.date('m').DIRECTORY_SEPARATOR.date('d').DIRECTORY_SEPARATOR.$pageID.DIRECTORY_SEPARATOR;
                        
                        //upload the image
                        $uploader = new fileUploader();
                        if($uploader->preparePath($imagePath)){
                            $uploader->copyJPEG($_FILES['pict']['tmp_name'],$imagePath.'image.jpg',640,480);
                            $uploader->copyJPEG($imagePath.'image.jpg',$imagePath.'thumb.jpg',90,70);

                            //mark image with a copyrigh text
                            $uploader->mark($imagePath.'image.jpg',$GLOBALS['_CONFIG']['server_root']);
                        }   
                    }
                    
                    /*
                        Sending Confirmation E-Mail to User
                        The basic idea is to prepare all the necessary data and then prefetch
                        a text based template by smarty. Then the output of this template
                        is passed to the e-mail gateway, which will send the e-mail to the end
                        user.
                    */
                    $this->smarty->assign(array(
                                                'confString'    =>  $confirmCode,
                                                'pageURL'       =>  $pageURL
                                                ));
                                                
                    $text = $this->smarty->preFetch('emails/confirmInserat.txt');
					// $html = $this->smarty->preFetch('emails/confirmInserat.html');
                    $myMailer = new mailGateway();
                    $myMailer->send($_POST['mail'],'Listing - '.$_POST['title'],$text,$GLOBALS['_CONFIG']['bot']);
                    
                    
                    //reset antibot sessions
                    unset($_SESSION['botNumber']);
                    session_commit();
                    
                    //log action
                    $this->log->recordAction("Added a new listing");
                    
					//put e-mail address into a cookie
                    setcookie('iMail',$_POST['mail'],time()+60*60*24*365,'/');

                    //redirect browser to confirmation page 
                    header('Location: '.$GLOBALS['_CONFIG']['server_root'].$_GET['data'].'/'.$pageURL.'.html?do=added');
                    exit;
 
                }else{ //yes, there are errors
                    //tell smarty to report errors to the user   
                    $this->smarty->assign("error",$errors);
                } //if errors
            }else{
              //check if the client already submitted something in the past
              if(isset($_COOKIE['iMail'])){
                $_POST['mail'] = $_COOKIE['iMail'];
              }
            }//if post
        }

        
        /**
         * Creates a portion of the neccessary SQL in order to filter the overall
         * recordset.
         *
         * @return string
         */
        private function getFilter(){
            //check if there was a filter change request
            if(isset($_GET['filter'])){
                switch($_GET['filter']){
                    case 'selling': {$_SESSION['filter'] = 'selling'; break;}
                    case 'seeking': {$_SESSION['filter'] = 'seeking'; break;}
                    default:        {$_SESSION['filter'] = null;      break;}
                }   
            }
            
            //check what filter was set by the user
            switch($_SESSION['filter']){
                case 'selling': return 'AND ins_type = 1'; 
                case 'seeking': return 'AND ins_type = 2';
                default:        return null;
            }
        }
        
        
        /**
         * clientNodeIfolder::setTemplate()
         * 
         * set the action template to page.html
         * 
         * @return void
         **/
        public function setTemplate(){
            $this->setActionTemplate('ifolder.html');
        }
        
        
        /**
         * Sets the ID of the pagetype corresponsing to an inserat
         *
         */
        private function setInseratPageType(){
            $this->inseratPageType = (int)$this->db->getOne("SELECT id FROM datatype WHERE codeset = 'inserat'");
            if($this->inseratPageType == 0){
                throw new Exception("No Inserat Datatype Registered with the system!");   
            }
        }
    }
?>